import { defineStore } from "pinia";
import { userLogin, getUserdetail } from "@/utils/api/user.js";
import { isEmptyObject } from "@/utils/base";

export const useUserStore = defineStore("userStore", {
  state: () => ({
    userInfo: {},
    userToken: null,
    userId: null
  }),
  actions: {
    async userLoginInit(loginForm) {
      const res = await userLogin(loginForm);
      console.log(res);
      if (!res.success) {
        return false;
      }
      const { userId, userToken } = res.data || {};
      this.userToken = userToken;
      this.userId = userId;
      const isAdmin = await this.getUserInfo(userId);
      if (isAdmin) {
        localStorage.setItem("userToken", userToken);
      }
      return isAdmin;
    },
    async getUserInfo(user_id) {
      const userRes = await getUserdetail(user_id);
      if (!userRes.success) {
        return false;
      }
      this.userInfo = userRes.data;
      if (this.userInfo.user_role !== "admin") {
        return false;
      }
      localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
      return true;
    },
    getLocalUserInfo() {
      if (isEmptyObject(this.userInfo) && !this.userToken) {
        const userInfo = localStorage.getItem("userInfo");
        const userToken = localStorage.getItem("userToken");
        if (userInfo && userToken) {
          this.userInfo = JSON.parse(userInfo);
          this.userToken = userToken;
        }
      }
      return {
        userInfo: this.userInfo,
        userToken: this.userToken
      };
    },
    clearUserInfo() {
      this.userInfo = {};
      this.userToken = null;
      localStorage.removeItem("userInfo");
      localStorage.removeItem("userToken");
    }
  }
});
